import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
  {path: '/', redirect: '/login'},
  {path: '/login', name:'Login', component:()=>import('../components/Login.vue')},
  {
path: '/home', 
  name: 'Home',
  redirect:'/welcome', 
  component:()=>import('../components/Home.vue'),
    children:[{
      path:'/welcome',
      name:'Welcome',
      component:()=>import('../components/Welcome.vue') 
    }, {
      path:'/users',
      name:'Users',
      component:()=>import('../components/user/Users.vue') 
    },{
      path:'/rights',
      name:'Rights',
      component:()=>import('../components/power/Rights.vue') 
    },{
      path:'/roles',
      name:'Roles',
      component:()=>import('../components/power/Roles.vue') 
    },{
      path:'/categories',
      name:'Cate',
      component:()=>import('../components/goods/Cate.vue') 
    },{
      path:'/params',
      name:'Params',
      component:()=>import('../components/goods/Params.vue') 
    }]
}
]

// 解决路由冗余
const originalPush = VueRouter.prototype.push
   VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  // 获取缓存的token进行判断
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token的时候跳转。
  if (!tokenStr) return next('/login')
  next()
})

export default router
